/**
 * Created by zengxm on 12/29/2016.
 */
const waterfall=require('async').waterfall
const sshConnect=require('../service.ssh').connect
const U=require("../../core/Utils")
const logger = U.logger("APT-ALIYUN")
const Format=require("util").format

//ubuntu 的版本号及其代号
const versions={
    "12.04":"Precise",
    "12.10":"Quantal",
    "13.04":"Raring",
    "13.10":"Saucy",
    "14.04":"Trusty",
    "14.10":"Utopic",
    "15.04":"Vivid"
}

const sourcesFile="/etc/apt/sources.list"

function _error(msg,ssh) {
    return function (err) {
        logger.error(msg+" : "+(typeof(err)==='string'?err:err.message))
        ssh.dispose()
    }
}

exports.run=(hosts,options)=>{
    hosts.forEach(host=>{
        const ssh=sshConnect(host, ()=>{
            logger.info("检测 Ubuntu version...")
            ssh.exec("cat /etc/issue",[],{}).then((result)=>{
                var v=/\s([^ ]*)\s/.exec(result) || []
                var version=versions[parseFloat(v[1])+""]
                if(version){
                    //先备份
                    logger.info("备份"+sourcesFile+"...")
                    ssh.execCommand(Format("cp %s %s.%s", sourcesFile,sourcesFile, U.date("yyyyMMdd")),{}).then(result=>{
                        if(result.code!=0)
                            return _error("执行 apt-get update 失败",ssh)(result.stderr)

                        //写入新的内容
                        const sources="deb http://mirrors.aliyun.com/ubuntu/ #version# main restricted universe multiverse\\n" +
                            "deb http://mirrors.aliyun.com/ubuntu/ #version#-security main restricted universe multiverse\\n" +
                            "deb http://mirrors.aliyun.com/ubuntu/ #version#-updates main restricted universe multiverse\\n" +
                            "deb http://mirrors.aliyun.com/ubuntu/ #version#-proposed main restricted universe multiverse\\n" +
                            "deb http://mirrors.aliyun.com/ubuntu/ #version#-backports main restricted universe multiverse\\n" +
                            "deb-src http://mirrors.aliyun.com/ubuntu/ #version# main restricted universe multiverse\\n" +
                            "deb-src http://mirrors.aliyun.com/ubuntu/ #version#-security main restricted universe multiverse\\n" +
                            "deb-src http://mirrors.aliyun.com/ubuntu/ #version#-updates main restricted universe multiverse\\n" +
                            "deb-src http://mirrors.aliyun.com/ubuntu/ #version#-proposed main restricted universe multiverse\\n" +
                            "deb-src http://mirrors.aliyun.com/ubuntu/ #version#-backports main restricted universe multiverse"

                        ssh.execCommand("echo -e \""+sources.replace(/#version#/g, version.toLowerCase())+"\" > "+sourcesFile,{}).then(echoResult=>{
                            if(echoResult.code!=0)
                                return _error("执行 apt-get update 失败",ssh)(echoResult.stderr)

                            logger.info("写入 "+sourcesFile+" done!")

                            ssh.connection.exec("apt-get update", function(err, stream) {
                                if (err) {
                                    return _error("执行 apt-get update 失败",ssh)(err)
                                };
                                stream.on('close', function (code, signal) {
                                    if(code==0)
                                        logger.info("更新Aliyun源成功！")
                                    ssh.dispose()
                                }).on('data', function (data) {
                                    logger.log(data.toString('utf-8',0,data.length-1))
                                }).stderr.on('data', function (data) {
                                    logger.error(data.toString('utf-8',0,data.length-1))
                                });
                            })

                        }, _error("写入 "+sourcesFile))
                    },_error("备份 "+sourcesFile,ssh))
                }
                else{
                    logger.error("暂不支持此版本："+v)
                    ssh.dispose()
                }
            },_error("检测版本出错",ssh))
        })
    })
}